------------------------------------------------
--Author Info
------------------------------------------------
SWEP.Author             = "Rothon"
SWEP.Contact            = "steven@facklerfamily.org"
SWEP.Purpose            = "Sends iris codes through stargates"
SWEP.Instructions       = "Right click to set, Left click to send"
SWEP.Category						= "Stargate"
------------------------------------------------

SWEP.Spawnable = true
SWEP.Adminspawnable = true
-- First person Model
SWEP.ViewModel = "models/v_gdo.mdl"
SWEP.ViewModelFOV = 80
-- Third Person Model
SWEP.WorldModel = "models/w_gdo.mdl"
-- Weapon Details
SWEP.Primary.Clipsize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Primary.Delay = 2
SWEP.Secondary.Clipsize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.timeClicked = 0

SWEP.gate = nil

local function SendCode(EntTable)
	local code = tonumber(EntTable.Owner:GetInfo("cl_weapon_gdo_iriscode"))
	local gate_pos = EntTable.gate.Target:GetPos()
	local iris_comp = EntTable:FindEnt(gate_pos, {"iris_computer"})
	if iris_comp and (SERVER) then
		local answer = iris_comp:RecieveIrisCode(code)
		if answer == 1 then
			EntTable.Owner:ChatPrint("IDC accepted, Iris opened")
		elseif answer == 0 then
			EntTable.Owner:ChatPrint("IDC rejected")
		else
			EntTable.Owner:ChatPrint("IDC accepted")
		end
--	elseif EntTable.gate:HasWire() then
--		EntTable.gate.Target:WireIrisControle(code)
	end
end

function SWEP:Reload()
end

function SWEP:Think()
end

function SWEP:PrimaryAttack()
	if(CLIENT) then return end
	local pos = self.Owner:GetPos()
	local sa = {"stargate_sg1", "stargate_atlantis"}
	self.gate = self:FindEnt(pos, sa)
	if(self.gate and self.gate.IsOpen) then
		-- modified from teta-bonitas nuke
		self.Weapon:SetNextPrimaryFire( CurTime() + self.Primary.Delay + 1 )
		self.Weapon:SendWeaponAnim(ACT_VM_PRIMARYATTACK)
		timer.Simple(self.Primary.Delay, SendCode, self)
	end
end

function SWEP:SecondaryAttack()
	if(CLIENT) then return end
	umsg.Start("gdo_openpanel", self.Owner)
	umsg.End()
end

function SWEP:FindEnt(pos, TableOEnts) -- modified from avon's dhd function
	local nearest
	local entDist = 2000 -- max distance to ent
	local foundEnts = {}
	for _,ent in pairs(TableOEnts) do
		for _,v in pairs(ents.FindByClass(ent)) do
			table.insert(foundEnts,v)
		end
	end
	for _,v in pairs(foundEnts) do
		local foundEnt_dist = (pos - v:GetPos()):Length()
		if entDist >= foundEnt_dist then
			entDist = foundEnt_dist
			nearest = v
		end
	end
	return nearest
end
